package com.sx.pipeline.utils.kml;

import com.sx.mvvmlibs.utils.Logs;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: YY
 * @Date: 2022/8/4
 * @Desc: TODO
 */
public class KmlHelper {

    /**
     * 解析Kml文件
     * @param file 文件对象
     *
     * TODO: 调用此方式 请使用单独线程
     */
    public List<FileParseBean> parseKml(File file) {
        try (InputStream is = new FileInputStream(file)) {
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String result = new String(buffer, StandardCharsets.UTF_8);
            // 解析数据
            return parseXmlWithDom4j(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用Dom4j解析 xml节点
     * @param xml 节点
     */
    private List<FileParseBean> parseXmlWithDom4j(String xml) {
        Logs.d("parseXmlWithDom4j " + xml);
        List<FileParseBean> fileParseBeanList = new ArrayList<>();
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            // 读取xml字符串，并转成输入流
            document = saxReader.read(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
            // 获取文档的根节点
            Element root = document.getRootElement();
            // 获取节点名称
            Element node = root.element("Document");
            // 迭代当前节点下面的所有子节点
            Iterator<Element> iterator = node.elementIterator();
            while (iterator.hasNext()) {
                Element e = iterator.next();
                listNodes(e, fileParseBeanList);
            }
            return fileParseBeanList;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return fileParseBeanList;
    }

    private void listNodes(Element node, List<FileParseBean> fileBeanList) {
        FileParseBean fileParseBean = new FileParseBean();
        List<FileParseBean.NodesBean> coordinateList = new ArrayList<>();
        try {
            if ("Placemark".equals(node.getName())) {
                String name = node.elementText("name");
                Logs.e("名字1", name);
                fileParseBean.setName(name);

                // 迭代当前节点下面的所有子节点
                Iterator<Element> iterator = node.elementIterator();
                while (iterator.hasNext()) {
                    Element e = iterator.next();
                    Logs.e("名字2", e.getName());
                    if ("Polygon".equals(e.getName())) {
                        Logs.e("面-名字", e.getName());
                        fileParseBean.setType(1);
                        Element i1 = node.element("Polygon");
                        Element i2 = i1.element("outerBoundaryIs");
                        Element i3 = i2.element("LinearRing");
                        String nodeContent = i3.elementText("coordinates");
                        String[] nodeContentSplit = nodeContent.trim().split(" ");
                        for (String nodeStr : nodeContentSplit) {
                            String[] polygonArray = nodeStr.split(",");
                            if (polygonArray.length > 1) {
                                FileParseBean.NodesBean bean = new FileParseBean.NodesBean(
                                        Double.parseDouble(polygonArray[0]), Double.parseDouble(polygonArray[1]));
                                coordinateList.add(bean);
                            }
                        }
                        fileParseBean.setNodesBeans(coordinateList);

                    } else if ("Point".equals(e.getName())) {
                        Logs.e("点-名字", e.getName());
                        fileParseBean.setType(0);
                        Element i1 = node.element("Point");
                        String nodeContent = i1.elementText("coordinates");
                        String[] nodeContentSplit = nodeContent.trim().split(",");
                        FileParseBean.NodesBean bean = new FileParseBean.NodesBean(
                                Double.parseDouble(nodeContentSplit[0]), Double.parseDouble(nodeContentSplit[1]));
                        coordinateList.add(bean);
                        fileParseBean.setNodesBeans(coordinateList);

                    } else if ("LineString".equals(e.getName())) {
                        Logs.e("线-名字", e.getName());
                        fileParseBean.setType(2);
                        //遍历Point节点的所有子节点
                        Element i1 = node.element("LineString");
                        String nodeContent = i1.elementText("coordinates");
                        String[] nodeContentSplit = nodeContent.trim().split(" ");
                        for (String nodeStr : nodeContentSplit) {
                            String[] lineArray = nodeStr.split(",");
                            if (lineArray.length > 1) {
                                FileParseBean.NodesBean bean = new FileParseBean.NodesBean(
                                        Double.parseDouble(lineArray[0]), Double.parseDouble(lineArray[1]));
                                coordinateList.add(bean);
                            }
                        }
                        fileParseBean.setNodesBeans(coordinateList);
                    }
                }
                fileBeanList.add(fileParseBean);
            }
        } catch (Exception e) {
            Logs.d("解析KML格式异常");
            e.printStackTrace();
        }

        // 同时迭代当前节点下面的所有子节点
        Iterator<Element> iterator = node.elementIterator();
        while (iterator.hasNext()) {
            Element e = iterator.next();
            listNodes(e, fileBeanList);
        }
    }
}
